package com.xizi.lotterySystem.service.Impl;

import com.xizi.lotterySystem.common.exception.ServiceException;
import com.xizi.lotterySystem.common.exception.errorCode.GlobalErrorCodeConstants;
import com.xizi.lotterySystem.common.exception.errorCode.ServiceErrorCodeConstants;
import com.xizi.lotterySystem.common.pojo.Constants;
import com.xizi.lotterySystem.dao.mapper.UserMapper;
import com.xizi.lotterySystem.service.IVerificationCodeService;
import com.xizi.lotterySystem.utils.CaptchaUtil;
import com.xizi.lotterySystem.utils.EmailSenderUtil;
import com.xizi.lotterySystem.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.xizi.lotterySystem.common.pojo.Constants.EMAIL_LOGIN_SUFFIX;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    private static final Logger log = LoggerFactory.getLogger(VerificationCodeServiceImpl.class);

    private static final long EXTENDED_TIME  = 60l;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String email) {
        int count = userMapper.selectCountByEmail(email);
        if(count == 0){
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        if(count > 1){
            log.error("存在一个账户对应多个邮箱！");
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR);
        }
        String verificationCode = CaptchaUtil.get();
        EmailSenderUtil.sendEmail(email ,verificationCode);
        redisUtil.set(email + EMAIL_LOGIN_SUFFIX,verificationCode,EXTENDED_TIME);
    }
}
